package framework;

import java.util.LinkedList;

import org.newdawn.slick.GameContainer;

public class BasicBuffer<T> implements Buffer<T> {

	
	protected LinkedList<BufferedElement<T>> q;
	
	private int conservationTime;
	
	public BasicBuffer() {
		q = new LinkedList<>();
		conservationTime = 800;
	}

	@Override
	public void update(GameContainer gc, int delta) {
		for (int i=0; i < q.size(); i++) {
			q.get(i).update(gc, delta);
			if (q.get(i).getCurrentTime() > getConservationTime()) {
				q.remove(i);
			}
		}
	}

	@Override
	public int getConservationTime() {
		return conservationTime;
	}

	@Override
	public void setConservationTime(int conservationTime) {
		this.conservationTime = conservationTime;
	}
	
	@Override
	public void buffer(T element) {
		q.push(new BufferedElement<T>(element));
	}

	@Override
	public T consume() {
		return q.size() > 0 ? q.pop().getElement() : null;
	}
	
	@Override
	public T getTop() {
		return q.size() > 0 ? q.getFirst().getElement() : null;
	}
	
	@Override
	public boolean contains(T element) {
		boolean contains = false;
		for(BufferedElement<T> e : this.q) {
			contains |= (e.getElement().equals(element));
		}
		return contains;
	}
	
	@Override
	public void remove(T element) {
		for(int i=0; i < q.size(); i++) {
			if (q.get(i).getElement().equals(element)) {
			   q.remove(q.get(i));
			}
		}
	}
	
	public class BufferedElement<E> implements Updatable {
		
		private int currentTime;
		
		private E e;

		public BufferedElement(E e) {
			currentTime = 0;
			this.e = e;
		}
		
		public int getCurrentTime() {
			return currentTime;
		}

		public E getElement() {
			return e;
		}

		public void setCurrentTime(int currentTime) {
			this.currentTime = currentTime;
		}

		public void setElement(E e) {
			this.e = e;
		}

		@Override
		public void update(GameContainer gc, int delta) {
			this.currentTime += delta;
		}	
	}
}
